package com.zenithmind.document.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.document.mapper.DocumentPermissionMapper;
import com.zenithmind.document.pojo.domain.DocumentPermission;
import com.zenithmind.document.pojo.dto.DocumentPermissionCreateDTO;
import com.zenithmind.document.pojo.dto.DocumentPermissionUpdateDTO;
import com.zenithmind.document.pojo.query.DocumentPermissionQueryDTO;
import com.zenithmind.document.pojo.vo.DocumentPermissionVO;
import com.zenithmind.document.service.DocumentPermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文档权限服务实现类
 * 遵循单一职责原则：专注于权限管理
 * 遵循依赖倒置原则：依赖抽象接口而不是具体实现
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DocumentPermissionServiceImpl extends ServiceImpl<DocumentPermissionMapper, DocumentPermission> implements DocumentPermissionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocumentPermissionVO createPermission(DocumentPermissionCreateDTO createDTO) {
        log.info("创建权限: documentId={}, targetType={}, targetId={}", 
                createDTO.getDocumentId(), createDTO.getTargetType(), createDTO.getTargetId());
        
        DocumentPermission permission = new DocumentPermission();
        BeanUtils.copyProperties(createDTO, permission);
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        
        save(permission);
        
        return convertToVO(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePermission(String id, DocumentPermissionUpdateDTO updateDTO) {
        log.info("更新权限: id={}", id);
        
        DocumentPermission permission = getById(id);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        BeanUtils.copyProperties(updateDTO, permission);
        permission.setUpdateTime(LocalDateTime.now());
        
        return updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deletePermission(String id) {
        log.info("删除权限: id={}", id);
        
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeletePermissions(List<String> ids) {
        log.info("批量删除权限: ids={}", ids);
        
        return removeByIds(ids);
    }

    @Override
    public IPage<DocumentPermissionVO> getPermissionPage(DocumentPermissionQueryDTO queryDTO) {
        log.info("分页查询权限");
        
        Page<DocumentPermissionVO> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        
        return baseMapper.selectPermissionPageWithDetails(page, queryDTO);
    }

    @Override
    public DocumentPermissionVO getPermissionDetail(String id) {
        log.info("获取权限详情: id={}", id);
        
        DocumentPermission permission = getById(id);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        return convertToVO(permission);
    }

    @Override
    public List<DocumentPermissionVO> getDocumentPermissions(String documentId) {
        log.info("获取文档权限列表: documentId={}", documentId);
        
        return baseMapper.selectDocumentPermissions(documentId);
    }

    @Override
    public List<DocumentPermissionVO> getUserPermissions(String userId) {
        log.info("获取用户权限列表: userId={}", userId);
        
        return baseMapper.selectUserPermissions(userId);
    }

    @Override
    public Boolean checkUserPermission(String documentId, String userId, String permission) {
        log.info("检查用户权限: documentId={}, userId={}, permission={}", documentId, userId, permission);
        
        return baseMapper.checkUserPermission(documentId, userId, permission);
    }

    @Override
    public Boolean checkRolePermission(String documentId, String roleId, String permission) {
        log.info("检查角色权限: documentId={}, roleId={}, permission={}", documentId, roleId, permission);
        
        return baseMapper.checkRolePermission(documentId, roleId, permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean grantUserPermissions(String documentId, String userId, List<String> permissions, String grantorId) {
        log.info("授予用户权限: documentId={}, userId={}, permissions={}", documentId, userId, permissions);
        
        return baseMapper.grantUserPermissions(documentId, userId, permissions, grantorId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean revokeUserPermissions(String documentId, String userId, List<String> permissions) {
        log.info("撤销用户权限: documentId={}, userId={}, permissions={}", documentId, userId, permissions);
        
        return baseMapper.revokeUserPermissions(documentId, userId, permissions) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean grantRolePermissions(String documentId, String roleId, List<String> permissions, String grantorId) {
        log.info("授予角色权限: documentId={}, roleId={}, permissions={}", documentId, roleId, permissions);
        
        return baseMapper.grantRolePermissions(documentId, roleId, permissions, grantorId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean revokeRolePermissions(String documentId, String roleId, List<String> permissions) {
        log.info("撤销角色权限: documentId={}, roleId={}, permissions={}", documentId, roleId, permissions);
        
        return baseMapper.revokeRolePermissions(documentId, roleId, permissions) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyPermissions(String sourceDocumentId, String targetDocumentId) {
        log.info("复制权限: sourceDocumentId={}, targetDocumentId={}", sourceDocumentId, targetDocumentId);
        
        return baseMapper.copyPermissions(sourceDocumentId, targetDocumentId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean inheritPermissions(String parentDocumentId, String childDocumentId) {
        log.info("继承权限: parentDocumentId={}, childDocumentId={}", parentDocumentId, childDocumentId);
        
        return baseMapper.inheritPermissions(parentDocumentId, childDocumentId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setDefaultPermissions(String documentId, Object permissions) {
        log.info("设置默认权限: documentId={}", documentId);
        
        return baseMapper.setDefaultPermissions(documentId, permissions) > 0;
    }

    @Override
    public List<String> getEffectivePermissions(String documentId, String userId) {
        log.info("获取有效权限: documentId={}, userId={}", documentId, userId);
        
        return baseMapper.selectEffectivePermissions(documentId, userId);
    }

    @Override
    public Object getPermissionTree(String documentId) {
        log.info("获取权限树: documentId={}", documentId);
        
        return baseMapper.selectPermissionTree(documentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchSetPermissions(List<String> documentIds, Object permissions) {
        log.info("批量设置权限: documentIds={}", documentIds);
        
        return baseMapper.batchSetPermissions(documentIds, permissions) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cleanupExpiredPermissions() {
        log.info("清理过期权限");
        
        return baseMapper.cleanupExpiredPermissions();
    }

    @Override
    public Object auditPermissions(String documentId) {
        log.info("权限审计: documentId={}", documentId);
        
        return baseMapper.auditPermissions(documentId);
    }

    @Override
    public List<Object> getPermissionChangeHistory(String documentId, Integer limit) {
        log.info("获取权限变更历史: documentId={}, limit={}", documentId, limit);
        
        return baseMapper.selectPermissionChangeHistory(documentId, limit);
    }

    @Override
    public Object exportPermissionConfig(String documentId) {
        log.info("导出权限配置: documentId={}", documentId);
        
        return baseMapper.exportPermissionConfig(documentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean importPermissionConfig(String documentId, Object config) {
        log.info("导入权限配置: documentId={}", documentId);
        
        return baseMapper.importPermissionConfig(documentId, config) > 0;
    }

    @Override
    public Object validatePermissionConfig(Object config) {
        log.info("验证权限配置");
        
        return baseMapper.validatePermissionConfig(config);
    }

    @Override
    public List<Object> getPermissionTemplates() {
        log.info("获取权限模板");
        
        return baseMapper.selectPermissionTemplates();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean applyPermissionTemplate(String documentId, String templateId) {
        log.info("应用权限模板: documentId={}, templateId={}", documentId, templateId);
        
        return baseMapper.applyPermissionTemplate(documentId, templateId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createPermissionTemplate(String name, Object config) {
        log.info("创建权限模板: name={}", name);
        
        return baseMapper.createPermissionTemplate(name, config);
    }

    @Override
    public Object getPermissionStatistics(String documentId) {
        log.info("获取权限统计: documentId={}", documentId);
        
        return baseMapper.selectPermissionStatistics(documentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean syncPermissions(String documentId) {
        log.info("同步权限: documentId={}", documentId);
        
        return baseMapper.syncPermissions(documentId) > 0;
    }

    /**
     * 转换为VO对象
     */
    private DocumentPermissionVO convertToVO(DocumentPermission permission) {
        DocumentPermissionVO vo = new DocumentPermissionVO();
        BeanUtils.copyProperties(permission, vo);
        return vo;
    }
}
